package com.lijianan.Controller;

import com.lijianan.Controller.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    // 手动添加日志记录器
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取资源访问路径uri
        String uri = request.getRequestURI();

        //2.判断资源是否需要拦截，登录不需要拦截 /login
        if (uri.contains("/login") || uri.contains("/register")) {
            filterChain.doFilter(request,response);
            return;
        }

        //3.如果资源需要拦截，判断token是否存在，如果存在，放行，如果不存在，拦截
        String token = request.getHeader("token");
        if(token==null || token.isEmpty()){
            log.info("令牌不存在，请登录！");
            response.setStatus(401);
            return;
        }
        //5. 解析token，如果解析失败，返回错误结果（未登录）。
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(401);
            return;
        }
        log.info("令牌合法，放行。");
        System.out.println("ok");
        //5.解析的token是正确的
        filterChain.doFilter(request,response);
    }
}